<script>
import 'element-ui/lib/theme-chalk/index.css';
import { ThirdPartyLoginApi } from '@/services/Public';
import { checkItemConfigApi } from '@/services/SystemSetting';
import MapVue from '../../Map/Map.vue'
export default {
  data () {
    return {
      userInfo: {
      },
      data: [
        {
          name: 'parent',
          children: [
            { name: 'children' }
          ]
        }
      ],
      // 记录新开的标签页
      opendWindow: {},
      user: {}
    }
  },
  created () {
    let userInfo = window.localStorage.getItem('userInfo') || '{}'
    this.userInfo = JSON.parse(userInfo)
  },
  computed: {
    getNavList () {
      let store = this.$store.state.sideNav
      let local = window.localStorage.getItem('platFormSideNav') || '[]'
      local = JSON.parse(local)
      let sideNav = store.length > 0 ? store : local

      return sideNav
      // let store = this.$store.state.userMenu
      // let local = window.localStorage.getItem('platUserMenu') || '[]'
      // local = JSON.parse(local)
      // let sideNav = store.length > 0 ? store : local

      // return sideNav
    },
    activeTab () {
      let store = this.$store.state.activeTab
      let local = window.localStorage.getItem('platFormActiveTab')
      let name = store === '' ? store : local
      return name
    },
    isLeftNavCollapse () {
      let isCollapseState = this.$store.state.isLeftNavCollapse
      return isCollapseState || false
    },
    isLeftNavHidden () {
      let state = this.$store.state.isLeftNavHidden
      return state || false
    },
    // 通过isCollapse和isHidden判断是否显示左侧菜单
    isLeftNavShow () {
      console.log(this.isLeftNavCollapse, this.isLeftNavHidden)
      if (this.isLeftNavHidden) {
        return !this.isLeftNavCollapse
      } else {
        return this.isLeftNavCollapse
      }
    },
    // 获取已选择项目
    choosedProject () {
      let project = this.$store.state.choosedProject
      return project
    }
  },
  methods: {
    // 点击左侧菜单时将路由添加到标签栏中
    addActiveTabs (nav, floor, upperMenu) {
      // console.log(nav, floor, upperMenu, 'click')
      // let token = window.sessionStorage.getItem('access_token')
      let token = window.localStorage.getItem('access_token')

      if (nav.menu_type === '1') {
        this.$store.dispatch('setActiveTabs', nav)
        this.$router.push({
          path: '/' + nav.route_url
        })
      } else if (nav.menu_type === '2') {
        console.log('测试', nav, floor, upperMenu)
        var strRouteUrl = nav.route_url;
        if (strRouteUrl == '') {
          this.$message.warning("当前菜单的URL或路由不能为空,请在'公共中心-应用管理'页面下进行确认");
        } else if (strRouteUrl != '' && (strRouteUrl.indexOf("http://") != -1 || strRouteUrl.indexOf("https://") != -1)) {//如果有http就判断是其它的网站
          // 判断链接中是否带了参数，如果带了，直接用&拼接
          let param = ''
          let link = nav.outer_url + param
          let newLink = this.handleUrl(link)
          // 判断当前链接是否打开过，如果打开，关闭之前的tab
          if (this.opendWindow[newLink]) {
            this.opendWindow[newLink].close()          }
          this.opendWindow[newLink] = window.open(newLink)
          // window.open(strRouteUrl)
        } else {
          checkItemConfigApi.checkSystemBind({
            data: {
              app_sys_no: nav.system_app_no,
              user_id: this.userInfo.user_id
            }
          }).then(res => {
            if (res.code === 0) {
              window.open('http://' + nav.app_domain_name + '/redirect?path=/' + nav.route_url + '&access_token=' + res.data.access_token)
            } else if (res.code === 33199) {
              this.$message.warning('未绑定系统，请先在"个人中心-我的应用"页面中任意点击一个路由进行绑定后再操作')
            }
          })
        }
      } else {
        // this.thirdPartyLogin(nav.outer_url)
      }
    },
    // 处理url，将所需参数注入
    handleUrl (link = '') {
      // 解析url，获得目标网址
      let host = link.split('?')[0]
      // 获取携带的参数
      let params = link.split('?')[1] ? link.split('?')[1].split('&') : []
      // 处理后的数组
      let res = []
      params.map((item) => {
        // 遍历参数列表，解析出key和要携带的值
        let key = item.split('=')[0]
        let value = item.split('=')[1]
        // 判断是否是动态注入参数还是普通参数  
        let reg = /^\$\{.*\}$/
        let str = ''
        if (reg.test(value)) {
          // 因为分割出的值是类似{user.short_key}格式的，需要把前后的大括号去掉
          let valueLen = value.length
          // 最后得到user.short_key这样的格式，表示全局有一个user对象，取其中short_key的值
          value = value.substr(2, valueLen - 3)
          let targetObj = value.split('.')[0]
          let targetObjKey = value.split('.')[1]

          if (this[targetObj]) {
            str = key + '=' + this[targetObj][targetObjKey]
          } else {
            str = key + '=' + ''
          }
        } else {
          str = key + '=' + value
        }
        res.push(str)
      })
      let newLink = host + '?' + res.join('&')
      return newLink
    },
    // 跳转到外部子系统
    thirdPartyLogin (platform) {
      ThirdPartyLoginApi.thirdPartyLogin({
        params: {
          platform: platform
        }
      }).then(res => {
        console.log(res, 'third party')
        if (res.code === 0) {
          window.open(res.data.url + '?token=' + res.data.token + '&sid=' + res.data.sid)
        }
      })
    }
  },
  render () {
    // 根据是否有children_list分别生成submenu或者menuitem
    // 渲染时，记录所处的层级及其上级的菜单编号列表
    let renderMenu = (menuList, floor, upperMenuList) => {
      return menuList.map(item => {
        if (item.route_url === '') {
          item.route_url = item.outer_url
        }
        if (item.children_list && item.children_list.length > 0) {
          return (
            <el-submenu {...{ attrs: { 'index': item.menu_id, 'key': item.menu_id } }}>
              <template slot="title">
                <i {...{ attrs: { 'class': (!item.menu_css ? 'fa-bars' : item.menu_css) + ' fa' } }}></i>
                <span>{item.menu_name}</span>
              </template>
              {
                renderMenu(item.children_list, floor + 1, [])
              }
            </el-submenu>
          )
        } else {
          return (
            <el-menu-item onClick={() => this.addActiveTabs(item, floor, upperMenuList)} {...{
              attrs: {
                'key': item.menu_id, 'index': item.route_url,
                'class': (item.route_url === this.activeTab ? 'active' : '') + ' el-menu-item'
              }
            }}>
              <i {...{ attrs: { 'class': (!item.menu_css ? 'fa-bars' : item.menu_css) + ' fa' } }}></i>
              <span slot="title">{item.menu_name}</span>
            </el-menu-item>
          )
        }
      })
    }
    return (
      <el-menu {...{
        attrs: { 'class': 'el-menu-vertical-demo el-menu user-menu', 'collapse': this.isLeftNavCollapse },
        props: { 'router': false, 'text-color': '#ffffffa6', 'background-color': '#001529' }
      }}>

        {
          renderMenu(this.getNavList, 1, [])
        }
      </el-menu>
    )
  }
}
</script>
<style scoped lang="scss">
.el-menu-vertical-demo {
  .el-submenu {
    .el-submenu__title {
      .fa {
        margin-right: 14px;
      }
    }
  }
  .el-menu-item {
    .fa {
      margin-right: 14px;
    }
  }
}
.el-menu {
  width: 100%;
  // color: #ffffffa6;
  background-color: #001529;
  padding-top: 20px;

  .el-menu-item {
    color: rgba(255, 255, 255, 0.65);
    &.is-active {
      // background-color: #1890ff;
      // color: #fff;
      background-color: #1890ff !important;
      color: #fff !important;
      .fa {
        color: #fff !important;
      }
    }
    &.active {
      // color: #409eff;
      background-color: #1890ff !important;
      color: #fff !important;
      .fa {
        color: #fff !important;
      }
    }
  }
  .fa {
    margin-right: 14px;
  }
  .menu-name {
    color: #fff;
    opacity: 0.65;
  }
}
/deep/.el-menu {
  border: none;
}
.menu {
  width: 100%;
  // width: 210px;
  height: 40px;
  text-align: center;
  line-height: 40px;
}
.el-menu:not(.el-menu--collapse) {
  width: 100%;
}
.el-menu-vertical-demo:not(.el-menu--collapse) {
  width: 100%;
  min-height: 400px;
  overflow-y: scroll;
  &::-webkit-scrollbar {
    /*滚动条整体样式*/
    width: 0px; /*高宽分别对应横竖滚动条的尺寸*/
    height: 0px;
  }
}
</style>
